package com.exam.api.config.validation.validator;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

import java.math.BigDecimal;


public class DecimalPointValidator implements ConstraintValidator<DecimalPoint, BigDecimal> {
    /**
     * 小数点位数
     */
    private int decimalPointNum;

    @Override
    public void initialize(DecimalPoint decimalPoint) {
        decimalPointNum = decimalPoint.value();
    }

    @Override
    public boolean isValid(BigDecimal value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) {
            return true;
        }
        if (value.scale() > decimalPointNum) {
            HibernateConstraintValidatorContext hibernateContext = constraintValidatorContext.unwrap(HibernateConstraintValidatorContext.class);
            hibernateContext.addMessageParameter("value", decimalPointNum);
            hibernateContext.buildConstraintViolationWithTemplate("小数点后最多{value}位").addConstraintViolation();
            return false;
        }
        return true;
    }
}
